package com.pethome.web.controller;


import com.alibaba.fastjson2.JSON;
import com.pethome.common.annotation.Log;
import com.pethome.common.constant.Constants;
import com.pethome.common.core.controller.BaseController;
import com.pethome.common.core.domain.AjaxResult;
import com.pethome.common.core.domain.entity.Customer;
import com.pethome.common.core.domain.model.LoginBody;
import com.pethome.common.core.domain.model.LoginUser;
import com.pethome.common.core.domain.model.RegisterBody;
import com.pethome.common.core.page.TableDataInfo;
import com.pethome.common.enums.BusinessType;
import com.pethome.common.utils.MessageUtils;
import com.pethome.common.utils.SecurityUtils;
import com.pethome.common.utils.ServletUtils;
import com.pethome.common.utils.StringUtils;
import com.pethome.common.utils.poi.ExcelUtil;
import com.pethome.framework.manager.AsyncManager;
import com.pethome.framework.manager.factory.AsyncFactory;
import com.pethome.framework.web.service.TokenService;
import com.pethome.system.service.ISysConfigService;
import com.pethome.web.service.ICustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 客户信息Controller
 * 
 * @author hjc
 * @date 2024-08-25
 */
@Slf4j
@RestController
@RequestMapping("/web/customer")
public class CustomerController extends BaseController {
    @Autowired
    private ICustomerService customerService;

    @Autowired
    private TokenService tokenService;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        log.info("顾客登录=============" + loginBody.toString());
        // 生成令牌
        Map<String,Object> map = customerService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, map.get("token"));
        ajax.put("CustomerId",map.get("customerId"));
        ajax.put("customerName",map.get("customerName"));
        ajax.put("customerAvatar",map.get("customerAvatar"));
        return ajax;
    }


    @Autowired
    private ISysConfigService configService;

    @PostMapping("/register")
    public AjaxResult register(@RequestBody RegisterBody user) {
        log.warn("顾客注册" + user.toString());
        String msg = customerService.register(user);
        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }


    @GetMapping("/getInfo")
    public AjaxResult getInfo() {

        log.warn("获取xinxi  =======> getInfo");

        Customer user = SecurityUtils.getLoginUser().getCustomer();
        Customer customer = customerService.selectCustomerByCustomerId(user.getCustomerId());

        System.out.println(user.toString());
        AjaxResult ajax = AjaxResult.success();
//        ajax.put("user", user);
        ajax.put("id", user.getCustomerId());
        ajax.put("avatar", customer.getCustomerAvatar());
        ajax.put("username",user.getCustomerName());
        return ajax;
    }


    @PostMapping("/logout")
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
//        获取登录用户
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
//            顾客
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, MessageUtils.message("user.logout.success")));
        }
        ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.success(MessageUtils.message("user.logout.success"))));
    }



//==========================================================================

    @GetMapping("/getInfo2")
    public AjaxResult getInfo2() {
        log.warn("个人信息页面");
        Customer user = SecurityUtils.getLoginUser().getCustomer();
        Customer customer = customerService.selectCustomerByCustomerId(user.getCustomerId());
        AjaxResult ajax = AjaxResult.success();

        return success(customer);
    }

    /**
     * 修改客户信息
     */

    @PutMapping("/update")
    public AjaxResult update(@RequestBody Customer customer)
    {
        return toAjax(customerService.updateCustomer(customer));
    }














//==========================================================================


    /**
     * 查询客户信息列表
     */
    @PreAuthorize("@ss.hasPermi('web:customer:list')")
    @GetMapping("/list")
    public TableDataInfo list(Customer customer)
    {
        startPage();
        List<Customer> list = customerService.selectCustomerList(customer);
        return getDataTable(list);
    }

    /**
     * 导出客户信息列表
     */
    @PreAuthorize("@ss.hasPermi('web:customer:export')")
    @Log(title = "客户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Customer customer)
    {
        List<Customer> list = customerService.selectCustomerList(customer);
        ExcelUtil<Customer> util = new ExcelUtil<Customer>(Customer.class);
        util.exportExcel(response, list, "客户信息数据");
    }

    /**
     * 获取客户信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('web:customer:query')")
    @GetMapping(value = "/{customerId}")
    public AjaxResult getInfo(@PathVariable("customerId") Long customerId)
    {
        return success(customerService.selectCustomerByCustomerId(customerId));
    }

    /**
     * 新增客户信息
     */
    @PreAuthorize("@ss.hasPermi('web:customer:add')")
    @Log(title = "客户信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Customer customer)
    {
        return toAjax(customerService.insertCustomer(customer));
    }

    /**
     * 修改客户信息
     */
    @PreAuthorize("@ss.hasPermi('web:customer:edit')")
    @Log(title = "客户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Customer customer)
    {
        return toAjax(customerService.updateCustomer(customer));
    }

    /**
     * 删除客户信息
     */
    @PreAuthorize("@ss.hasPermi('web:customer:remove')")
    @Log(title = "客户信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{customerIds}")
    public AjaxResult remove(@PathVariable Long[] customerIds)
    {
        return toAjax(customerService.deleteCustomerByCustomerIds(customerIds));
    }

    /**
     * 恢复客户信息
     */
//    @PreAuthorize("@ss.hasPermi('web:customer:remove')")
//    @Log(title = "客户信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/reCustomer/{customerId}")
    public AjaxResult reCustomer(@PathVariable Long customerId)
    {
        return toAjax(customerService.reCustomer(customerId));
    }
    /**
     * 恢复客户信息
     */
//    @PreAuthorize("@ss.hasPermi('web:customer:remove')")
//    @Log(title = "客户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/LaHeiCustomer/{customerId}")
    public AjaxResult LaHeiCustomer(@PathVariable Long customerId)
    {
        return toAjax(customerService.LaHeiCustomer(customerId));
    }
}
